//
//  ZhuCeViewController.m
//  NC-Trendy
//
//  Created by ljd on 16/2/24.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "ZhuCeViewController.h"

#import "NSString+Password.h"

#import "WoDeTableViewController.h"

@interface ZhuCeViewController ()<UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *userZhuCeNameField;
@property (weak, nonatomic) IBOutlet UITextField *userZhuCeMiMaField;
@property (weak, nonatomic) IBOutlet UITextField *userQueRenZhuCeMMField;
@property (weak, nonatomic) IBOutlet UITextField *userTelField;
@property (weak, nonatomic) IBOutlet UITextField *userEmailField;
@property (weak, nonatomic) IBOutlet UITextField *userSexField;
@property (weak, nonatomic) IBOutlet UITextField *userLocationField;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *completeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *userIconImageVIew;

@end

@implementation ZhuCeViewController

//打开本机相册，选择相片的方法
- (IBAction)chooseUserIconBtnClick:(UIButton *)sender {
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    pick.delegate = self;
    //设置选择的路径是相册
    [pick setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    //设置选择照片时，画面（模态）跳转的方式是覆盖上去的方式
    [pick setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    //设置允许编辑
    [pick setAllowsEditing:YES];
    //点击这个按键，跳转到选择图片控制器
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark -UIImagePickController代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    //将选择好的图片转成data类型，选择画质是高画质
    NSData *data = UIImageJPEGRepresentation(image, 0);
    //将图片的data信息写入到本地的缓存目录下
    [data writeToFile:[self imagePath] atomically:YES];
    //设置用户头像的imageview的图片是缓存路径下的图片
    self.userIconImageVIew.image = [UIImage imageWithContentsOfFile:[self imagePath]];
    //图片选择控制器消失，回到注册页面
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
//图片选择控制器点击取消的时候，执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//封装的方法：封装缓存的路径
-(NSString *)imagePath {
    //
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"iconImage.jpg"];
    return path;
}

//加密
-(NSString *)miMaJiaMi {
    return [self.userQueRenZhuCeMMField.text MD5];
}
//显示提示封装
-(void)showAlertView:(NSString *)alert{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:alert delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
//点击提示上面按键的方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        NSLog(@"123");
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//上传除了用户头像信息之外的注册信息的方法
-(void)shangChuanPuTongXinXi {
    //如果两次输入的密码一致
    if ([self.userZhuCeMiMaField.text isEqualToString:self.userQueRenZhuCeMMField.text]) {
        //定义发送请求路径
        NSString *path = [NSString stringWithFormat:@"http://localhost:8888/nongchao/Home/User/regist"];
        //发送给php的参数
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
        mutDic[@"name"] = self.userZhuCeNameField.text;
        mutDic[@"pwd"] = self.miMaJiaMi;
        mutDic[@"tel"] = self.userTelField.text;
        mutDic[@"email"] = self.userEmailField.text;
        mutDic[@"sex"] = self.userSexField.text;
        mutDic[@"zone"] = self.userLocationField.text;
        //找到单例
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //发送POST，如果成功
        [manager POST:path parameters:mutDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //如果有返回项
            if (responseObject) {
                //显示提示，内容是返回项返回的data
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:responseObject[@"data"] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //如果失败，提示注册失败，并且打印error
            if (error) {
                NSLog(@"%@",error);
                [self showAlertView:@"注册失败，请您重尝试"];
            }
        }];

    }else{
        //两次输入密码不一致，提示重新输入密码
        [self showAlertView:@"您两次填写的密码不一致，请重新确认注册密码"];
        //将两个密码栏清空
        self.userQueRenZhuCeMMField.text = nil;
        self.userZhuCeMiMaField.text = nil;
    }
}


//上传用户头像的方法
-(void)shangChuanYongHuTouXiang {
    //定义发送请求的方法
    NSString *path = [NSString stringWithFormat:@"http://localhost:8888/nongchao/Home/User/uploadIcon/%@",@"UploadFile"];
    //发送POST请求给端口
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //定义一个图片，图片是缓存路径里面存储的图片（用户选择的作为头像的图片）
        UIImage *image = [UIImage imageWithContentsOfFile:[self imagePath]];
        //将图片转化为2进制
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        //
        [formData appendPartWithFileData:data name:@"icon" fileName:@"img.png" mimeType:@"text/html"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       //将服务器返回的数据用字典接收
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
       // [AppDelegate appdelegate].userModel.user_icon = [NSString ];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"%@",error);
        }
    }];

}

//注册方法封装
-(void)zhuCeFangFa {
    //如果有为空的textfield 就提示请填写完全注册信息,完成注册
    if ([self.userZhuCeMiMaField.text isEqualToString:@""]||[self.userZhuCeNameField.text isEqualToString:@""]||[self.userQueRenZhuCeMMField.text isEqualToString:@""]||[self.userTelField.text isEqualToString:@""]||[self.userEmailField.text isEqualToString:@""]||[self.userSexField.text isEqualToString:@""]||[self.userLocationField.text isEqualToString:@""]) {
        [self showAlertView:@"请填写完全注册信息,完成注册"];
    }else{
        //如果没有空的信息,但是用户不想上传图片
        NSLog(@"123");
        if (self.userIconImageVIew.image == nil) {
            //用户不想上传图片，直接调用上传其他信息的方法进行注册
            [self shangChuanPuTongXinXi];
        }else{
            //如果用户选择了图片，调用上传用户头像方法
            [self shangChuanPuTongXinXi];
            
            
        }
    
    }
}

//注册按键
- (IBAction)zhuCeBtnClick:(id)sender {
    [self zhuCeFangFa];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //将输入的密码变成黑点，不显示明文
    self.userZhuCeMiMaField.secureTextEntry = YES;
    self.userQueRenZhuCeMMField.secureTextEntry = YES;
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
